package com.bhs.sansonglogistics.ui.quality;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.bean.AdvancePayment;
import com.bhs.sansonglogistics.bean.DedicatedLineBean;
import com.bhs.sansonglogistics.bean.DedicatedLineDataBean;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.bean.QualityVoucherData;
import com.bhs.sansonglogistics.dialog.AttachMoreDialog2;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.QualityVoucherAdapter;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseSettlementActivity;
import com.bhs.sansonglogistics.ui.message.CircleDetailActivity;
import com.bhs.sansonglogistics.ui.mine.CommonProblemDetailActivity;
import com.bhs.sansonglogistics.ui.order.BluetoothConfigurationActivity;
import com.bhs.sansonglogistics.ui.wallet.PayDeskActivity;
import com.bhs.sansonglogistics.utils.FastCilckOneUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.OneClickLoginUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 品质专线充值
 */
public class QualityVoucherActivity extends BaseActivity implements View.OnClickListener, NetCallBack {


    private TextView mTvMore;
    private View mVBg;
    private LinearLayout mLlHint;
    private TextView mTvMore2;
    private LinearLayout mLlInfo;
    private LinearLayout mLlSingle;
    private TextView mTvSingleMoney;
    private LinearLayout mLlAll;
    private TextView mTvAllMoney;

    private Button mBtnSubmit;
    private Button mBtnOther;
    private int rechargeType = 1;//充值类型 1=单个 2=所有
    private TextView mTvSingleLabel;
    private TextView mTvAllLabel;
    private RecyclerView mRvNotUpgraded;
    private QualityVoucherAdapter notUpgradedAdapter;
    private QualityVoucherAdapter haveBeenUpgradedAdapter;
    private RecyclerView mRvHaveBeenUpgraded;
    private List<String> mList = new ArrayList<>();

    private double allMoney, singleMoney;
    private double singleTotalMoney;
    private TextView mTvNotUpgraded;
    private TextView mTvHaveBeenUpgraded;
    private LinearLayout mLlLine;
    private LinearLayout mLlAllHint;
    private TextView mTvAllHint;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private QualityVoucherData data;

    @Override
    public int initLayout() {
        return R.layout.activity_voucher;
    }

    @Override
    public void initView() {
        mTvMore = findViewById(R.id.tv_more);
        mVBg = findViewById(R.id.v_bg);
        mLlHint = findViewById(R.id.ll_hint);
        mTvMore2 = findViewById(R.id.tv_more2);
        mLlInfo = findViewById(R.id.ll_info);
        mLlSingle = findViewById(R.id.ll_single);
        mTvSingleMoney = findViewById(R.id.tv_single_money);
        mLlAll = findViewById(R.id.ll_all);
        mTvAllMoney = findViewById(R.id.tv_all_money);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mBtnOther = findViewById(R.id.btn_other);
        mTvSingleLabel = findViewById(R.id.tv_single_label);
        mTvAllLabel = findViewById(R.id.tv_all_label);
        mLlAll.setOnClickListener(this);
        mLlSingle.setOnClickListener(this);
        mRvNotUpgraded = findViewById(R.id.rv_not_upgraded);
        mRvHaveBeenUpgraded = findViewById(R.id.rv_have_been_upgraded);
        mTvMore2.setOnClickListener(this);
        mTvNotUpgraded = findViewById(R.id.tv_not_upgraded);
        mTvHaveBeenUpgraded = findViewById(R.id.tv_have_been_upgraded);
        mLlLine = findViewById(R.id.ll_line);
        mLlAllHint = findViewById(R.id.ll_all_hint);
        mTvAllHint = findViewById(R.id.tv_all_hint);
        mTvMore.setOnClickListener(this);
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                networkRequest(netApi.get_deposit_config_info(), QualityVoucherActivity.this, 11);
                if (result.getResultCode() != 1) {
                    networkRequest(netApi.getSpecialList(1, 100), QualityVoucherActivity.this, 666);
                }
            }
        });
    }

    @Override
    public void initData() {
        mList.add("申请退还");
        mList.add("缴纳记录");
        //mList.add("押金说明");
        notUpgradedAdapter = new QualityVoucherAdapter();
        mRvNotUpgraded.setAdapter(notUpgradedAdapter);
        mRvNotUpgraded.setLayoutManager(new GridLayoutManager(mActivity, 2));
        haveBeenUpgradedAdapter = new QualityVoucherAdapter();
        mRvHaveBeenUpgraded.setAdapter(haveBeenUpgradedAdapter);
        mRvHaveBeenUpgraded.setLayoutManager(new GridLayoutManager(mActivity, 2));
        notUpgradedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DedicatedLineBean data = notUpgradedAdapter.getData().get(position);
                data.setChecked(!data.isChecked());
                notUpgradedAdapter.notifyDataSetChanged();
                if (data.isChecked()) {
                    singleTotalMoney += singleMoney;
                } else {
                    singleTotalMoney -= singleMoney;
                }
                mBtnSubmit.setText(String.format("立即充值%s元", MyUtils.checkPoint(singleTotalMoney)));
            }
        });
        networkRequest(netApi.get_deposit_config_info(), this, 11);
        networkRequest(netApi.getSpecialList(1, 100), this, 666);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_single:
                if (rechargeType == 2) {
                    rechargeType = 1;
                    mBtnSubmit.setText(String.format("立即充值%s元", MyUtils.checkPoint(singleTotalMoney)));
                    mLlSingle.setBackgroundResource(R.drawable.border_blue_8);
                    mTvSingleLabel.setBackgroundResource(R.drawable.bg_single);
                    mLlAll.setBackgroundResource(R.drawable.border_grey_8);
                    mTvAllLabel.setBackgroundResource(R.drawable.bg_all);
                    mLlLine.setVisibility(View.VISIBLE);
                    mLlAllHint.setVisibility(View.GONE);

                }
                break;
            case R.id.ll_all:
                if (rechargeType == 1) {
                    rechargeType = 2;
                    mBtnSubmit.setText(String.format("立即充值%s元", MyUtils.checkPoint(allMoney)));
                    llAll();
                }
                break;
            case R.id.tv_more:
                AttachMoreDialog2 attachMoreDialog = new AttachMoreDialog2(mActivity, mList);
                new XPopup.Builder(mActivity).isTouchThrough(true).isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .atView(mTvMore).hasShadowBg(false) // 去掉半透明背景
                        .asCustom(attachMoreDialog).show();
                attachMoreDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        if (data != null) {
                            attachMoreDialog.dismiss();
                            if (id.equals("申请退还")) {
                                startActivity(new Intent(mActivity, RefundActivity.class)
                                        .putExtra("Switch", data.getData().getRefundDepositSwitch()));
                            } else if (id.equals("缴纳记录")) {
                                startActivity(new Intent(mActivity, VoucherListActivity.class));
                            } else if (id.equals("押金说明")) {
                                startActivity(new Intent(mActivity, CommonProblemDetailActivity.class)
                                        .putExtra("content", data.getData().getRepositRemark())
                                        .putExtra("title", "押金说明"));
                            }
                        } else {
                            ToastUtil.show("正在获取数据");
                        }
                    }
                });
                break;
            case R.id.btn_submit:
                //如果充值了单条专线在充全线给个提示
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (rechargeType == 2 && haveBeenUpgradedAdapter.getData().size() > 0) {
                    new XPopup.Builder(mActivity)
                            .asConfirm("提示", "您已经充值了单条专线了，确定继续充值全线吗",
                                    "取消", "确定",
                                    new OnConfirmListener() {
                                        @SuppressLint("NotifyDataSetChanged")
                                        @Override
                                        public void onConfirm() {
                                            submit();
                                        }
                                    }, null, false)
                            .show();
                } else {
                    submit();
                }
                break;
        }
    }

    private void llAll() {
        mLlSingle.setBackgroundResource(R.drawable.border_grey_8);
        mTvSingleLabel.setBackgroundResource(R.drawable.bg_all);
        mLlAll.setBackgroundResource(R.drawable.border_blue_8);
        mTvAllLabel.setBackgroundResource(R.drawable.bg_single);
        mLlLine.setVisibility(View.GONE);
        mLlAllHint.setVisibility(View.VISIBLE);
    }


    private void submit() {
        String line_ids;
        if (rechargeType == 1) {
            line_ids = CommaSplice();
        } else {
            line_ids = "-1";
        }
        if (TextUtils.isEmpty(line_ids)) {
            ToastUtil.show("请选择充值专线");
            return;
        }
        loadingPopupShow();
        networkRequest(netApi.create_deposit_order(line_ids), this, 22);
    }

    public String CommaSplice() {
        StringBuilder images = new StringBuilder();
        for (DedicatedLineBean mDatum : notUpgradedAdapter.getData()) {
            if (mDatum.isChecked()) {
                images.append(mDatum.getLine_id()).append(",");
            }
        }
        if (!TextUtils.isEmpty(images)) {
            images = new StringBuilder(images.substring(0, images.toString().lastIndexOf(",")));
        }
        return images.toString();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 666) {
            DedicatedLineDataBean bean = new Gson().fromJson(json, DedicatedLineDataBean.class);
            if (bean.isStatus()) {
                List<DedicatedLineBean> notUpgraded = new ArrayList<>();
                List<DedicatedLineBean> haveBeenUpgraded = new ArrayList<>();
                for (DedicatedLineBean dedicatedLineBean : bean.getData().getList()) {
                    if (dedicatedLineBean.getDeposit_status().equals("1")) {
                        haveBeenUpgraded.add(dedicatedLineBean);
                    } else {
                        notUpgraded.add(dedicatedLineBean);
                    }
                }
                notUpgradedAdapter.setNewData(notUpgraded);
                haveBeenUpgradedAdapter.setNewData(haveBeenUpgraded);
                if (!MyUtils.isEmpty(notUpgraded)) {
                    mTvNotUpgraded.setVisibility(View.VISIBLE);
                } else {
                    mTvNotUpgraded.setVisibility(View.GONE);
                }
                if (!MyUtils.isEmpty(haveBeenUpgraded)) {
                    mTvHaveBeenUpgraded.setVisibility(View.VISIBLE);
                } else {
                    mTvHaveBeenUpgraded.setVisibility(View.GONE);
                }
                mBtnSubmit.setText("立即充值");
                singleTotalMoney = 0;
            }
        } else if (requestCode == 11) {
            data = new Gson().fromJson(json, QualityVoucherData.class);
            if (data.isStatus()) {
                allMoney = Double.parseDouble(data.getData().getCompanyDeposit());
                singleMoney = Double.parseDouble(data.getData().getLineDeposit());
                mTvAllMoney.setText(String.format("%s元", MyUtils.checkPoint(allMoney)));
                mTvSingleMoney.setText(String.format("%s元", MyUtils.checkPoint(singleMoney)));
                if (data.getData().getCompany_deposit().equals("1")) {
                    llAll();
                    mLlSingle.setVisibility(View.GONE);
                    mTvAllHint.setText("已升级专线");
                    mBtnSubmit.setVisibility(View.GONE);
                }
            }
        } else if (requestCode == 22) {
            loadingPopupDismiss();
            AdvancePayment payment = new Gson().fromJson(json, AdvancePayment.class);
            if (payment.isStatus()) {
                Double money;
                if (rechargeType == 1) {
                    money = singleTotalMoney;
                } else {
                    money = allMoney;
                }
                intentActivityResultLauncher.launch(new Intent(mActivity, PayDeskActivity.class)
                        .putExtra("pay_sn", payment.getData().getOrder_id())
                        .putExtra("money", String.valueOf(money)));
            } else {
                ToastUtil.show(payment.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }
}